import yaml

# 从文件读取原始 YAML 数据
with open("工业图谱.yml", "r", encoding="utf-8") as f:
    raw_yaml = f.read()

# 解析 YAML 内容为 Python 对象
data = yaml.safe_load(raw_yaml)

# 自定义格式化函数，确保 key: value 在同一行，并控制缩进
def dump_yaml_fixed(d, indent=0):
    lines = []
    if isinstance(d, list):
        for item in d:
            if isinstance(item, dict):
                for k, v in item.items():
                    lines.append(' ' * indent + f"- {k}:")
                    lines += dump_yaml_fixed(v, indent + 2)
            else:
                lines.append(' ' * indent + f"- {item}")
    elif isinstance(d, dict):
        for k, v in d.items():
            if isinstance(v, (dict, list)):
                lines.append(' ' * indent + f"{k}:")
                lines += dump_yaml_fixed(v, indent + 2)
            else:
                # 如果键是 description，则为值添加双引号
                if k == "description":
                    # 如果值中已经包含双引号，则在前面添加转义符 \
                    if isinstance(v, str):
                        v = v.replace('"', '\\"')
                    lines.append(' ' * indent + f'{k}: "{v}"')
                else:
                    lines.append(' ' * indent + f"{k}: {v}")
    else:
        lines.append(' ' * indent + str(d))
    return lines

# 生成格式化后的 YAML 文本
formatted_yaml = '\n'.join(dump_yaml_fixed(data))

# 写入输出文件
with open("formatted_output.yml", "w", encoding="utf-8") as f:
    f.write(formatted_yaml)

print("✅ 格式化完成，结果已保存为 formatted_output.yml")
